import { request } from "@/utils/service"
import axios from "axios"
import { getToken } from "@/utils/cache/cookies"
import type { PlayRecordResponseData, FileRecordRequestData, FileRecordResponseData } from "./types/audio"

export function audios(data: FileRecordRequestData) {
  return request<FileRecordResponseData>({
    url: "audios",
    method: "post",
    data
  })
}

export function audio(data: FormData) {
  return request({
    url: "audio",
    method: "post",
    data
  })
}

export function play(id: string) {
  return axios.get(`/admin/play/${id}`, {
    headers: {
      Authorization: "Bearer " + getToken()
    },
    responseType: "arraybuffer"
  })
}

export function playRecords(id: string) {
  return request<PlayRecordResponseData>({
    url: `playrecord/${id}`,
    method: "get"
  })
}

export function del(id: string) {
  return request({
    url: `audio/${id}`,
    method: "delete"
  })
}

export function multiDel(ids: number[]) {
  return request({
    url: `audios`,
    method: "delete",
    data: { ids }
  })
}

export function exportLogs() {
  return axios
    .get(`/admin/export`, {
      headers: {
        Authorization: "Bearer " + getToken()
      },
      responseType: "blob"
    })
    .then((res) => {
      const blob = new Blob([res.data]) //处理文档流
      const fileName = "播放记录.xlsx"
      const elink = document.createElement("a")
      elink.download = fileName
      elink.style.display = "none"
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      console.log("elink.click()")
      elink.click()
      console.log("URL.revokeObjectURL(elink.href)")
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    })
}
